package com.zoe.onelink.doc.plugin.feign;

import cn.hutool.core.io.resource.ResourceUtil;
import com.zoe.onelink.doc.plugin.feign.model.FeignClientDoc;
import com.zoe.onelink.doc.plugin.feign.model.FeignClientTemplateParam;
import com.zoe.onelink.doc.plugin.feign.provider.FeignClientTemplateParamProvider;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-03-31
 */
@Slf4j
public class FeignOperationBuilderPlugin implements OperationBuilderPlugin {

    private static final String FEIGN_CLIENT_TEMPLATE_RESOURCE = "template/FeignClientTemplate.java";

    private String clientTemplate;
    private final FeignClientTemplateParamProvider feignClientTemplateParamProvider;

    public FeignOperationBuilderPlugin(FeignClientTemplateParamProvider feignClientTemplateParamProvider) {
        this.feignClientTemplateParamProvider = feignClientTemplateParamProvider;
        try {
            this.clientTemplate = ResourceUtil.readUtf8Str(FEIGN_CLIENT_TEMPLATE_RESOURCE);
        } catch (Exception e) {
            this.clientTemplate = null;
            log.warn("[接口文档] 加载Feign模板失败");
        }
    }

    @Override
    @SuppressWarnings("rawtypes")
    public void apply(OperationContext context) {
        FeignClientTemplateParam feignClientTemplateParam = this.feignClientTemplateParamProvider.generateParam(context);
        String clientText = feignClientTemplateParam.toTemplateText(this.clientTemplate);
        List<VendorExtension> vendorExtensions = new ArrayList<>();
        FeignClientDoc feignDoc = new FeignClientDoc();
        feignDoc.setFeignDefinition(clientText);
        feignDoc.setClasses(new ArrayList<>());
        vendorExtensions.add(new FeignVendorExtension("feignApi", feignDoc));
        context.operationBuilder().extensions(vendorExtensions);

    }


    @Override
    public boolean supports(DocumentationType documentationType) {
        return this.clientTemplate != null;
    }
}
